<template>
  <a-upload
      list-type="picture-card"
      :action="uploadCtr.url"
      :limit="uploadCtr.limit"
      :default-file-list="uploadCtr.fileList"
      image-preview
      :headers="uploadCtr.headers"
      @change="onChange"

  />
  <!--
    单图上传调用方法:
   <smart-upload-image v-model="formState.qrPhoto"/>onSuccess
   多图上传调用方法
    <smart-upload-image v-model="formState.qrPhoto" :limit="5"/>
  -->
</template>

<script setup name="smart-upload-image">

import {reactive} from "vue";
import {RequestConfig} from "@/libs/config";
import {useOperatorStore} from "@/libs/store";
import {EmptyUtil, StrUtil} from "@/utils";
import {UploadApi} from "@/libs/api";


const operatorStore = useOperatorStore()

const props = defineProps({
  limit: {
    type: Number,
    required: false,
    default: 1
  },
  modelValue: {
    type: [Array, String],
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const formatModelValue = () => {
  const {modelValue} = props;

  if (modelValue instanceof Array) {
    return [...modelValue]
  }
  if (EmptyUtil.isNotEmptyString(props.modelValue)) {

    return [{url: props.modelValue, uid: StrUtil.uuid(), name: StrUtil.uuid()}]
  }
  return []
}

const uploadCtr = reactive({
  limit: props.limit,
  url: `${RequestConfig.baseURL}${UploadApi.uploadImageUrl}`,
  headers: {
    authorization: `${RequestConfig.tokenPrefix}${operatorStore.getToken}`
  },
  fileList: formatModelValue(),
})


const onChange = (fileList) => {
  const rs = fileList.map(item => {
    const {response, uid, name} = item
    if (item?.response !== undefined) return {uid, name, url: response.data.url}
    return {uid, name, url: item.url}
  })

  if (props.modelValue instanceof Array) {
    emit('update:modelValue', rs)
    return
  }
  if (rs.length > 0) {

    emit('update:modelValue', rs[0].url)

  } else {
    emit('update:modelValue', null)
  }

}

</script>

